package com.app.web.service;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.app.modules.web.pagetag.Page;
import com.app.web.bean.Para;
import com.app.web.db.DBConn;
import com.app.web.db.MySqlPageSQL;

public class TestService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	public List<Para> findPara(Page page) throws SQLException {
		logger.debug("执行 {} 类的 {} 方法.",this.getClass().toString(),"List findPara(Page page)");
		
		List<Para> paraList = new ArrayList<Para>(); 
		String sql = "select id,type,language,value_str as valueStr,text from para";
		String countSql = MySqlPageSQL.getCountSql(sql);
		DBConn db = new DBConn();
		ResultSet rs = db.executeQuery(countSql);
		int totalCount = 0;

		if (rs.next())
			totalCount = rs.getInt(1);
		
		page.setTotalCount(totalCount);
		
		sql = MySqlPageSQL.getPageSQL(sql, page.getFirst()-1, page.getPageSize());
		rs = db.executeQuery(sql);
		ResultSetMetaData rsmd = rs.getMetaData();
		
		StringBuffer sbName = new StringBuffer();
		StringBuffer sbLabel = new StringBuffer();
		for(int i=0;i<rsmd.getColumnCount();i++){
			sbLabel.append(rsmd.getColumnLabel(i + 1));
			sbLabel.append(",");
			
			sbName.append(rsmd.getColumnName(i + 1));
			sbName.append(",");
		}
		logger.debug("总共有{}列，列名(别名)为：{}",new Object[]{rsmd.getColumnCount(),sbLabel.toString(),sbLabel.delete(sbLabel.length()-1, sbLabel.length())});
		logger.debug("总共有{}列，列名为：{}",new Object[]{rsmd.getColumnCount(),sbName.delete(sbName.length()-1, sbName.length())});
		
		while(rs.next()){
			Para para = new Para();
			para.setId(rs.getInt("id"));
			para.setLanguage(rs.getString("language"));
			para.setText(rs.getString("text"));
			para.setType(rs.getString("type"));
			para.setValueStr(rs.getInt("valueStr"));
			
			paraList.add(para);
		}
		return paraList;
	}

	public static void main(String[] args) throws SQLException {
		Page page = new Page(3);
		page.setPageNo(1);
		TestService testService = new TestService();
		List<Para> paraList = testService.findPara(page);
		for(Para para : paraList){
			StringBuffer sb = new StringBuffer();
			sb.append(para.getId()).append("   ").append(para.getLanguage()).append("   ").append(para.getText()).append("   ").append(para.getType()).append("   ").append(para.getValueStr());
			System.out.println(sb.toString());
		}
	}
}
